
import axios, { type AxiosRequestHeaders, type AxiosResponse } from "axios";

import { useUserInfoStore } from "@/stores/user";
import pinia from "@/stores";


// 配置新建一个 axios 实例
const service = axios.create({
  baseURL: "/sph",

  timeout: 50000,
});
/* 定义response对象的data接口 */
interface ResponseData<T> {
  code: number;
  data: T; //就是response.data.data的类型 后端真正给你的那个数据
  message: string;
}

// 添加请求拦截器
service.interceptors.request.use((config) => {

  const userInfoStore =  useUserInfoStore(pinia)
  const token =  userInfoStore.token
  if(token){
   ( config.headers as AxiosRequestHeaders).token = token 
  }

  return config;
});

// 添加响应拦截器
service.interceptors.response.use(
  async (response: AxiosResponse<ResponseData<any>, any>) => {
    // 对响应数据做点什么
    const res = response.data;

    switch (res.code) {
      case 200:
        return res.data;
      case 201:
        console.log(response.data.message);
        return Promise.reject();
      case 208:
        console.log(response.data.message);
        return Promise.reject();
      case 205: //支付中
        return res;
    }
     /* 成功数据的code值为20000/200 */
      // 统一的错误提示
    if(res.code !== 20000 && res.code !== 200) {
      alert('Error')
      // `token` 过期或者账号已在别处登录
      if(response.status === 401){
        const storeUserInfo = useUserInfoStore(pinia);
        storeUserInfo.reset();
        window.location.href = "/login"; // 去登录页
      }
      return Promise.reject(service.interceptors.response);
    }
    else {
      return res.data; 
    }
   
  },

  (error)=>{

    return Promise.reject(error);
  }
);

export default service;

